package com.mechat.ui.chats.item

import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.SimpleItemAnimator
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.custom.base.config.BaseConfig
import com.custom.base.entity.OkHttpBodyEntity
import com.custom.base.entity.PageModel
import com.custom.base.http.OkHttpFromBoy
import com.custom.base.http.OkHttpManager
import com.custom.base.http.SDOkHttpResoutCallBack
import com.custom.base.manager.SDActivityManager
import com.custom.base.mvp.BasePresenterImpl
import com.google.android.gms.common.util.CollectionUtils
import com.google.gson.Gson
import com.mechat.Constant
import com.mechat.R
import com.mechat.bean.ConversationChatListBean
import com.mechat.util.HttpRequest
import com.yanzhenjie.recyclerview.OnItemMenuClickListener
import com.yanzhenjie.recyclerview.SwipeMenu
import com.yanzhenjie.recyclerview.SwipeMenuBridge
import com.yanzhenjie.recyclerview.SwipeMenuCreator
import com.yanzhenjie.recyclerview.SwipeMenuItem
import io.rong.imkit.SpName
import io.rong.imkit.widget.FixedLinearLayoutManager
import org.json.JSONObject

/**
 */
class ItemPresenter : BasePresenterImpl<ItemContract.View>(), ItemContract.Presenter {
    var list = arrayListOf<ConversationChatListBean>()
    var adapter: ItemAdapter? = null
    var entity: ItemModel.Data? = null
    var mBundle: Bundle? = null
    val page = PageModel()

    override fun initBundle(bundle: Bundle) {
        mBundle = bundle
        mView?.apply {
            chatsRefreshLayout.setOnLoadMoreListener {
                page.nextPage()
                getLoadMoreData(bundle)
            }

            adapter = ItemAdapter(list, SDActivityManager.instance.lastActivity)
            val layoutManager: LinearLayoutManager = FixedLinearLayoutManager(mActivity)

            // 解决调用 notifyItemChanged 闪烁问题,取消默认动画
            (listView.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false

            chatsRefreshLayout.setEnableLoadMore(list.size % page.pageSize == 0)
            // 创建菜单
            val mSwipeMenuCreator: SwipeMenuCreator = object : SwipeMenuCreator {
                override fun onCreateMenu(
                    leftMenu: SwipeMenu,
                    rightMenu: SwipeMenu,
                    position: Int
                ) {
                    val itemViewType: Int = adapter!!.getItemViewType(position)
                    if (itemViewType == -200) {
                        return
                    }
                    val width: Int = mActivity.resources.getDimensionPixelSize(R.dimen.dimen_65dp)

                    // 1. MATCH_PARENT 自适应高度，保持和Item一样高;
                    // 2. 指定具体的高，比如80;
                    // 3. WRAP_CONTENT，自身高度，不推荐;
                    val height = ViewGroup.LayoutParams.MATCH_PARENT

                    val topItem: SwipeMenuItem =
                        SwipeMenuItem(mActivity).setBackgroundColor(Color.parseColor("#785FFF"))
                            .setImage(if (list[position].toppingFlag != 1) R.drawable.ic_chats_item_top else R.drawable.ic_chats_item_un_top)
                            .setText(if (list[position].toppingFlag != 1) "Topping" else "Cancel\n" + "Topping")
                            .setTextColor(Color.WHITE)
                            .setWidth(width)
                            .setHeight(height)
                    rightMenu.addMenuItem(topItem) // 添加菜单到右侧。

                    val deleteItem: SwipeMenuItem =
                        SwipeMenuItem(mActivity).setBackgroundColor(Color.parseColor("#FF465D"))
                            .setImage(R.drawable.ic_chats_item_delete)
                            .setText("Delete")
                            .setTextColor(Color.WHITE)
                            .setWidth(width)
                            .setHeight(height)
                    rightMenu.addMenuItem(deleteItem) // 添加菜单到右侧。


                }
            }
            // 设置监听器。
            listView.setSwipeMenuCreator(mSwipeMenuCreator)
            val mItemMenuClickListener: OnItemMenuClickListener =
                object : OnItemMenuClickListener {
                    override fun onItemClick(menuBridge: SwipeMenuBridge, position: Int) {
                        // 任何操作必须先关闭菜单，否则可能出现Item菜单打开状态错乱。
                        menuBridge.closeMenu()
                        HttpRequest.commonNotify("UserListMenu",if(menuBridge.position == 0) if (list[position].toppingFlag != 1) "Topping" else "CancelTopping" else "Delete")
                        OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
                            override fun addBody(requestBody: OkHttpBodyEntity) {
                                requestBody.setPost(Constant.chat_op_url)
                                requestBody.add(
                                    "modelUserCode",
                                    bundle.getString("modelUserCode") ?: ""
                                )
                                requestBody.add(
                                    "userGroupLabel",
                                    bundle.getString("modelUserCode") ?: ""
                                )
                                requestBody.add("userCodeFriend", list[position].userCode)
                                requestBody.add("targetId", list[position].targetId)
                                requestBody.add(
                                    "opType",
                                    if (menuBridge.position == 0) if (list[position].toppingFlag != 1) 3 else 4 else 5
                                )
                                requestBody.add("conversationType", 1)
                                requestBody.add(
                                    "chatterUserCode",
                                    BaseConfig.getInstance.getString(SpName.userCode, "")
                                )
                            }
                        }, object : SDOkHttpResoutCallBack<ItemModel>() {
                            override fun onSuccess(entity: ItemModel) {
                                if (menuBridge.position == 1) {
                                    list.removeAt(position)
                                }
                                if (menuBridge.position == 0) {
                                    if (list[position].toppingFlag != 1) {
                                        list[position].toppingFlag =
                                            if (list[position].toppingFlag == 1) 0 else 1
                                        val changeItem = list[position]
                                        list.removeAt(position)
                                        list.add(0, changeItem)
                                    } else {
                                        var lastTopping = 0
                                        for (i in 0 until list.size) {
                                            if (list[i].toppingFlag == 1) {
                                                lastTopping = i
                                            }
                                        }
                                        list[position].toppingFlag =
                                            if (list[position].toppingFlag == 1) 0 else 1
                                        val changeItem = list[position]
                                        list.removeAt(position)
                                        list.add(lastTopping, changeItem)
                                    }
                                }
                                adapter?.notifyDataSetChanged()
                            }
                        })
                    }
                }

            // 菜单点击监听。
            listView.setOnItemMenuClickListener(mItemMenuClickListener)
            listView.layoutManager = layoutManager
            listView.adapter = adapter
        }
    }

    private fun getLoadMoreData(bundle: Bundle) {
        mView?.apply {
            OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
                override fun addBody(requestBody: OkHttpBodyEntity) {
                    requestBody.setPost(Constant.chat_model_chats_list_url)
                    requestBody.addPage(page)
                    requestBody.add("modelUserCode", bundle.getString("modelUserCode") ?: "")
                }
            }, object : SDOkHttpResoutCallBack<ItemModel>() {
                override fun onSuccess(entity: ItemModel) {
                    if (entity.data != null) {
                        if (!CollectionUtils.isEmpty(entity.data.conversationChatList)) {
                            for (i in 0 until entity.data.conversationChatList.size) {
                                Glide.with(mActivity)
                                    .load(entity.data.conversationChatList[i].avatarUrl)
                                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                                    .preload()
                            }

                            list.addAll(entity.data.conversationChatList)
                            chatsRefreshLayout.setEnableLoadMore(entity.data.conversationChatList.size == page.pageSize)
                            adapter?.notifyDataSetChanged()
                        }
                    } else {
                        page.rollbackPage()
                        chatsRefreshLayout.setEnableLoadMore(false)
                    }
                }

                override fun onFailure(code: Int, msg: String) {
                    super.onFailure(code, msg)
                    page.rollbackPage()
                }

                override fun onFinish() {
                    super.onFinish()
                    chatsRefreshLayout.finishLoadMore()
                }
            })
        }
    }

    fun setData() {
        mView?.apply {
            list.clear()
            if (entity != null) {
                if (!CollectionUtils.isEmpty(entity!!.conversationChatList)) {
                    for (i in 0 until entity!!.conversationChatList.size) {
                        Glide.with(mActivity)
                            .load(entity!!.conversationChatList[i].avatarUrl)
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .preload()
                    }

                    list.addAll(entity!!.conversationChatList)
                    chatsRefreshLayout.setEnableLoadMore(entity!!.conversationChatList.size == page.pageSize)
                    adapter?.notifyDataSetChanged()
                }
                chatsRefreshLayout.visibility =
                    if (CollectionUtils.isEmpty(entity!!.conversationChatList)) View.GONE else View.VISIBLE
                emptyContainer.visibility =
                    if (CollectionUtils.isEmpty(entity!!.conversationChatList)) View.VISIBLE else View.GONE
            } else {
                chatsRefreshLayout.visibility = if (entity == null) View.GONE else View.VISIBLE
                emptyContainer.visibility = if (entity == null) View.VISIBLE else View.GONE
                chatsRefreshLayout.setEnableLoadMore(false)
            }

        }
    }

    fun getDataSize(modelUserCode: String) {
        OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
            override fun addBody(requestBody: OkHttpBodyEntity) {
                requestBody.setPost(Constant.chat_model_chats_list_url)
                requestBody.addPage(page)
                requestBody.add("modelUserCode", modelUserCode)
            }
        }, object : SDOkHttpResoutCallBack<ItemModel>() {
            override fun onSuccess(entity: ItemModel) {
                this@ItemPresenter.entity = entity.data
                setData()
            }
        })
    }

    fun refreshItem(data: String) {
        val jsonObject = JSONObject(data)
        if (mBundle?.getString("modelUserCode") == jsonObject.getString("modelUserCode")) {
            val bean = Gson().fromJson(
                jsonObject.getString("userAccount"),
                ConversationChatListBean::class.java
            )
            var isExist=false
            for (item in list) {
                if (item.targetId == bean.targetId) {
                    isExist= true
                    if (bean.toppingFlag == 1) {
                        list.remove(item)
                        list.add(0, bean)
                    } else {
                        var firstNoTopping = 0
                        for (i in 0 until list.size) {
                            if (list[i].toppingFlag == 0) {
                                firstNoTopping = i
                                break
                            }
                        }
                        list.remove(item)
                        list.add(firstNoTopping, bean)

                    }
                    break
                }
            }
            if (!isExist){
                if (bean.toppingFlag == 1) {
                    list.add(0, bean)
                } else {
                    var firstNoTopping = 0
                    for (i in 0 until list.size) {
                        if (list[i].toppingFlag == 0) {
                            firstNoTopping = i
                            break
                        }
                    }
                    list.add(firstNoTopping, bean)

                }
            }
            adapter?.notifyDataSetChanged()
        }
    }

    fun refreshItemOnline(data: String){
        val jsonObject = JSONObject(data)
        if (mBundle?.getString("modelUserCode") == jsonObject.getString("modelUserCode")) {
            for (i in 0 until list.size){
                if (list[i].userCode==jsonObject.getString("userCode")){
                    list[i].online = jsonObject.getInt("online")
                    adapter?.notifyItemChanged(i)
                    break
                }
            }

        }
    }
    fun refreshItemUnread(data: String){
        val jsonObject = JSONObject(data)
        Log.e("~~~", "refreshItemUnread: $jsonObject")
        Log.e("~~~", "refreshItemUnread: "+jsonObject.getString("modelUserCode") )
        if (mBundle?.getString("modelUserCode") == jsonObject.getString("modelUserCode")) {
            val bean = Gson().fromJson(
                jsonObject.getString("userAccount"),
                ConversationChatListBean::class.java
            )
            for (i in 0 until list.size){
                if (list[i].userCode==bean.userCode){
                    list[i].unReadNum = bean.unReadNum
                    adapter?.notifyItemChanged(i)
                    break
                }
            }

        }
    }
    override fun refresh() {
        page.initialRefresh()
    }
}